#![allow(non_snake_case)]

use std::ffi::c_void;

use android_logger::Config;
use app::{shutdown, AppInfo};
use exception::IO_EXCEPTION;
use jni::{
    objects::{JObject, JString},
    sys::{jint, JNI_VERSION_1_6},
    JNIEnv, JavaVM,
};
use log::{error, info, LevelFilter};

use crate::error::AppErr;

mod app;
mod exception;

#[no_mangle]
pub extern "system" fn JNI_OnLoad(_vm: JavaVM, _: *mut c_void) -> jint {
    android_logger::init_once(Config::default().with_max_level(LevelFilter::Debug));
    info!("jni onload success");
    JNI_VERSION_1_6
}

fn run_impl(env: &mut JNIEnv, store_path: JString) -> Result<(), AppErr> {
    let path = env.get_string(&store_path)?;
    AppInfo::init_once(path.to_str()?.to_owned());
    Ok(())
}

#[no_mangle]
pub extern "system" fn Java_com_hontech_webback_NativeService_run(
    mut env: JNIEnv,
    _obj: JObject,
    store_path: JString,
) {
    match run_impl(&mut env, store_path) {
        Ok(()) => {}

        Err(e) => {
            _ = env.throw_new(IO_EXCEPTION, e.to_string());
        }
    };
}

#[no_mangle]
pub extern "system" fn Java_com_hontech_webback_NativeService_exit(_env: JNIEnv, _obj: JObject) {
    shutdown();
    error!("native service shout down");
}
